﻿
using Kingdee.CDP.WebApi.SDK.DataEntity;
using Mapster;
using NewLife;
using Newtonsoft.Json.Linq;
using Radius.NET.Application.Service.ApiList;
using Radius.NET.Application.Entity;
using Radius.NET.Core.Service;
using Magicodes.ExporterAndImporter.Core.Extension;
using Radius.NET.Application;
using Admin.NET.Application.Util.Extension;
using Admin.NET.Interface.Kingdee.Util.Extension;
using Radius.NET.Interface.Kingdee.Attributes;
using Radius.NET.Interface.Kingdee.Options;

namespace Radius.NET.Interface.Kingdee.Util;
/// <summary>
/// 金蝶云星空工具类
/// </summary>
public class KingdeeUtil : IScoped
{
    private readonly ApiConfigListService _apiConfigListService;

    private readonly SysConfigService _sysConfigService;

    private SysApiConfigList SysApiConfig { set; get; }

    /// <summary>
    /// 金蝶SDK
    /// </summary>
    private K3CloudApi K3CloudApiClient;

    public KingdeeUtil(ApiConfigListService apiConfigListService, SysConfigService sysConfigService)
    {
        _apiConfigListService = apiConfigListService;
        _sysConfigService = sysConfigService;
    }

    public async Task<KingdeeUtil> GetClient(string code)
    {
        SysApiConfig = await _apiConfigListService.GetApiConfigByCode(code);
        if (SysApiConfig.Status != StatusEnum.Enable)
            throw Oops.Oh("接口已禁用！").StatusCode(900);

        KingdeeConfig Config = await GetKindgdeeIcloudConfig(SysApiConfig.IsMaster);
        K3CloudApiClient = new K3CloudApi(Config.Adapt<ThirdPassPortInfo>(), 300000);
        return this;
    }

    #region 查询--传入查询参数对象
    /// <summary>
    /// 查询--传入查询参数对象
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    [Obsolete("该查询方法已经废弃，请使用Query<T>(FormId,Filter)")]
    public List<List<object>> Query(object content)
    {

        var response = K3CloudApiClient.ExecuteBillQuery(JsonConvert.SerializeObject(content));

        if (response.Count == 1)
        {
            var resultJObject = JArray.Parse(JsonConvert.SerializeObject(response[0]));

            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            if (queryNode != null)
            {
                var isSuccess = queryNode.Value<bool>();
                if (!isSuccess)
                {
                    var error = resultJObject.SelectToken("$..Errors");
                    throw Oops.Bah("kigdeeError:" + error[0]);
                }
            }
            TP.Wrapper("云星空保存成功返回值", "调用云星空查询接口成功后返回的数据json结构",
            $"##查询参数## {JsonConvert.SerializeObject(content)}",
            $"##返回结果## {JsonConvert.SerializeObject(response)}").LogInformation();
            return response;
        }
        return response;
    }
    #endregion

    #region 查询--传入表单ID、过滤字符串、查询字段
    /// <summary>
    /// 查询--传入表单ID、过滤字符串、查询字段
    /// </summary>
    /// <param name="FormId">表单ID</param>
    /// <param name="Filter">过滤条件</param>
    /// <param name="FieldKeys">查询字段以,间隔</param>
    /// <returns></returns>
    [Obsolete("该查询方法已经废弃，请使用Query<T>(FormId,Filter)")]
    public List<List<object>> Query(string FormId, string Filter, string[] FieldKeys)
    {
        var response = K3CloudApiClient.ExecuteBillQuery(JsonConvert.SerializeObject(new
        {
            FormId,
            FilterString = Filter,
            FieldKeys = string.Join(",", FieldKeys),
            Number = "",
            Id = ""
        }));
        if (response.Count == 1)
        {
            var resultJObject = JArray.Parse(JsonConvert.SerializeObject(response[0]));

            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            if (queryNode != null)
            {
                var isSuccess = queryNode.Value<bool>();
                if (!isSuccess)
                {
                    var error = resultJObject.SelectToken("$..Errors");
                    throw Oops.Bah("kigdeeError:" + error[0]);
                }
            }
            return response;
        }
        return response;
    }
    #endregion

    #region 查询--传入实体类
    /// <summary>
    /// 查询--传入实体类
    /// </summary>
    /// <param name="FormId">表单ID</param>
    /// <param name="Filter">过滤条件</param>
    /// <returns></returns>
    public List<T> Query<T>(string FormId, string Filter)
    {
        string FieldKeys = Activator.CreateInstance(typeof(T))!.ToKingdeeFieldKeys().Join(",");
        var data = new
        {
            FormId,
            FilterString = Filter,
            FieldKeys = FieldKeys,
            Number = "",
            Id = ""
        }.ToJson();
        TP.Wrapper("云星空查询接口", "云星空查询参数",
            $"##参数值## {data}").LogInformation();
        var response = K3CloudApiClient.ExecuteBillQuery(data);
        if (response.Count == 1)
        {
            var resultJObject = JArray.Parse(JsonConvert.SerializeObject(response[0]));

            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            if (queryNode != null)
            {
                var isSuccess = queryNode.Value<bool>();
                if (!isSuccess)
                {
                    var error = resultJObject.SelectToken("$..Errors");
                    throw Oops.Bah("kigdeeError:" + error[0]);
                }
            }
            return response.KingdeeToList<T>();
        }
        return response.KingdeeToList<T>();
    }
    #endregion

    #region 保存
    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="formId">表单ID</param>
    /// <param name="data">Model</param>
    /// <returns></returns>
    public object Save(string formId, object data)
    {
        string json = JsonConvert.SerializeObject(data);
        json.LogInformation();
        var response = K3CloudApiClient.Save(formId, json);

        var resultJObject = JObject.Parse(response);
        var queryNode = resultJObject.SelectToken("$..IsSuccess");
        if (queryNode is not null)
        {
            bool IsSuccess = queryNode.Value<bool>();
            if (!IsSuccess)
            {
                var error = resultJObject.SelectToken("$..Errors");
                throw Oops.Bah("kigdeeError:" + error?[0]);
            }
            string Number = resultJObject.SelectToken("$.Result.Number").ParseToString();
            TP.Wrapper("云星空保存成功返回值", "调用云星空保存接口成功后返回的数据json结构",
            $"##返回值## {JsonConvert.SerializeObject(resultJObject)}",
            $"##单据号Number## {Number}").LogInformation();

            var submitObj = new
            {
                CreateOrgId = 0,
                Numbers = new string[] { Number },
                Ids = "",
                SelectedPostId = 0,
                NetworkCtrl = "",
                IgnoreInterationFlag = ""
            };
            if (SysApiConfig.IsSubmit.Equals("Y"))
            {
                Submit(formId, submitObj);
            }

            return resultJObject.SelectToken("$");
        }
        return response;
    }
    #endregion

    #region 暂存
    public object Draft(string formId, object data)
    {
        var response = K3CloudApiClient.Draft(formId, JSON.Serialize(data));
        var resultJObject = Clay.Parse(response);

        if (resultJObject.IsDefined("Result"))
        {
            bool IsSuccess = resultJObject["Result"]["ResponseStatus"]["IsSuccess"];
            if (!IsSuccess)
            {
                var error = resultJObject["Result"]["ResponseStatus"]["Errors"][0];
                throw Oops.Bah("kigdeeError:" + error.Message);
            }

            string Number = resultJObject.SelectToken("$.Result.Number").ParseToString();
            TP.Wrapper("云星空暂存成功返回值", "调用云星空暂存接口成功后返回的数据json结构",
            $"##返回值## {JsonConvert.SerializeObject(resultJObject)}",
            $"##单据号Number## {Number}").LogInformation();

            return resultJObject.SelectToken("$");
        }
        return response;
    }
    #endregion

    #region 下推
    /// <summary>
    /// 下推
    /// </summary>
    /// <param name="formId">表单ID</param>
    /// <param name="data">Model</param>
    /// <returns></returns>
    public object Push(string formId, object data)
    {
        JSON.Serialize(data).LogInformation();
        var response = K3CloudApiClient.Push(formId, JSON.Serialize(data));
        response.LogInformation();
        var resultJObject = Clay.Parse(response);

        if (resultJObject.IsDefined("Result"))
        {
            bool IsSuccess = resultJObject["Result"]["ResponseStatus"]["IsSuccess"];
            if (!IsSuccess)
            {
                var error = resultJObject["Result"]["ResponseStatus"]["Errors"][0];
                throw Oops.Bah("kigdeeError:" + error.Message);
            }

            string Number = resultJObject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Number"];
            //SelectToken("$.Result.ResponseStatus.SuccessEntitys.Number").ParseToString();
            TP.Wrapper("云星空下推成功返回值", "调用云星空下推接口成功后返回的数据json结构",
            $"##返回值## {JsonConvert.SerializeObject(resultJObject)}",
            $"##单据号Number## {Number}").LogInformation();

            var submitObj = new
            {
                CreateOrgId = 0,
                Numbers = new string[] { Number },
                Ids = "",
                SelectedPostId = 0,
                NetworkCtrl = "",
                IgnoreInterationFlag = ""
            };

            if (SysApiConfig.IsSubmit.Equals("Y"))
            {
                Submit(formId, submitObj);
            }
            return resultJObject["Result"]["ResponseStatus"];
        }
        return response;
    }
    #endregion

    #region 查看
    /// <summary>
    /// 查看
    /// </summary>
    /// <param name="formId">表单ID</param>
    /// <param name="data">Model</param>
    /// <returns></returns>
    public object View(string formId, object data)
    {

        var response = K3CloudApiClient.View(formId, JSON.Serialize(data));
        //var response = await KingdeeConfig.PushUrl.SetBody(JsonConvert.SerializeObject(new { formId, data })).PostAsStringAsync();
        var resultJObject = Clay.Parse(response);
        return resultJObject;
    }
    #endregion

    #region 提交
    /// <summary>
    /// 提交
    /// </summary>
    /// <param name="formId"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public object Submit(string formId, object data)
    {
        var response = K3CloudApiClient.Submit(formId, JsonConvert.SerializeObject(data));
        var resultJObject = JObject.Parse(response);
        var queryNode = resultJObject.SelectToken("$..IsSuccess");
        if (queryNode is not null)
        {
            bool IsSuccess = queryNode.Value<bool>();
            if (!IsSuccess)
            {
                var error = resultJObject.SelectToken("$..Errors");
                throw Oops.Bah("kigdeeError:" + error?[0]);
            }
            if (SysApiConfig.IsAudit.Equals("Y"))
                Audit(formId, data);

            TP.Wrapper("云星空提交成功返回值", "调用云星空提交接口成功后返回的数据json结构",
            $"##提交参数## {JsonConvert.SerializeObject(data)}",
            $"##返回值## {resultJObject.SelectToken("$")}").LogInformation();
            return resultJObject.SelectToken("$");
        }
        return response;
    }
    #endregion

    #region 审核
    /// <summary>
    /// 审核
    /// </summary>
    /// <param name="formId"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public object Audit(string formId, object data)
    {
        var response = K3CloudApiClient.Audit(formId, JSON.Serialize(data));
        var resultJObject = JObject.Parse(response);
        var queryNode = resultJObject.SelectToken("$..IsSuccess");
        if (queryNode is not null)
        {
            bool IsSuccess = queryNode.Value<bool>();
            if (!IsSuccess)
            {
                var error = resultJObject.SelectToken("$..Errors");
                throw Oops.Bah("kigdeeError:" + error?[0]);
            }
            TP.Wrapper("云星空审核成功返回值", "调用云星空审核接口成功后返回的数据json结构",
            $"##提交参数## {JsonConvert.SerializeObject(data)}",
            $"##返回值## {resultJObject.SelectToken("$")}").LogInformation();
            return resultJObject.SelectToken("$");
        }
        return response;
    }
    #endregion

    #region 查看
    /// <summary>
    /// 查看
    /// </summary>
    /// <param name="data">Model</param>
    /// <returns></returns>
    public object QueryBusinessInfo(object data)
    {
        string json = JsonConvert.SerializeObject(data);
        var response = K3CloudApiClient.QueryBusinessInfo(json);
        var resultJObject = Clay.Parse(response);

        if (resultJObject.IsDefined("Result"))
        {
            bool IsSuccess = resultJObject["Result"]["ResponseStatus"]["IsSuccess"];
            if (!IsSuccess)
            {
                var error = resultJObject["Result"]["ResponseStatus"]["Errors"][0];
                throw Oops.Bah("kigdeeError:" + error.Message);
            }
            return response;
        }
        return response;
    }
    #endregion

    #region 获取金蝶云星空参数配置
    /// <summary>
    /// 获取金蝶云星空参数配置
    /// </summary>
    /// <param name="dbAccountType">账套类型</param>
    /// <returns></returns>
    [NonAction]
    private async Task<KingdeeConfig> GetKindgdeeIcloudConfig(string dbAccountType = "N")
    {
        if (dbAccountType == KingdeeConfigConst.IsMaster)
        {
            return new KingdeeConfig()
            {
                CloudUrl = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.BASEURL),
                CloudDbId = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.DBID),
                CloudUser = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.USERNAME),
                ApiAppId = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.APPID),
                AppSec = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.APPSECRET),
                Language = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.LCID),
                OrgId = KingdeeConfigConst.ORGID
            };
        }
        return new KingdeeConfig()
        {
            CloudUrl = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.BASEURL_TEST),
            CloudDbId = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.DBID_TEST),
            CloudUser = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.USERNAME_TEST),
            ApiAppId = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.APPID_TEST),
            AppSec = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.APPSECRET_TEST),
            Language = await _sysConfigService.GetConfigValue<string>(KingdeeConfigConst.LCID_TEST),
            OrgId = KingdeeConfigConst.ORGID
        };
    } 
    #endregion

}
